package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.manager.mapper.SysRoleMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.manager.service.SysRoleMenuService;
import com.atguigu.spzx.model.entity.system.SysMenu;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {
    @Resource
    SysMenuService sysMenuService;
    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;
    @Override
    public Map<String, Object> listRoleMenus(Long roleId) {
        Map<String, Object> map = new HashMap<>();
        //所有菜单嵌套列表
        List<SysMenu> menus = sysMenuService.listNestedMenus();
        //过滤出可用菜单列表:

        map.put("menus" , menus);
        //已分配的菜单id集合
        List<Long> checkedMenuIds = sysRoleMenuMapper.findCheckedMenuIds(roleId);

        map.put("checkedMenuIds",checkedMenuIds);
        return map;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignMenus2Role(Long roleId, List<Long> menuIds) {
        //1、先删除roleId所有已分配的菜单
        sysRoleMenuMapper.deleteMenusByRoleId(roleId);

        if(CollectionUtils.isEmpty(menuIds)){
            //如果menuIds为空 表示删除角色所有的菜单即可  不需要新分配
            return;
        }
        //2、新分配菜单
        sysRoleMenuMapper.assignMenus2Role(roleId , menuIds);
    }
}
